import fs from 'node:fs/promises'
import path from 'path'
import os from 'os'
import { shell } from 'electron'
const filePath = path.resolve('C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs')
const appData = path.join(os.homedir(), './AppData/Roaming')
const startMenu = path.join(appData, 'Microsoft\\Windows\\Start Menu\\Programs')
const fileLists: any = []
const isZhRegex = /[\u4e00-\u9fa5]/
const icondir = path.join(os.tmpdir(), 'ProcessIcon')
const getico = async (app) => {
  try {
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    const fileIcon = require('extract-file-icon')
    const buffer = fileIcon(app.desc, 32)
    const iconpath = path.join(icondir, `${app.name}.png`)
    try {
      await fs.access(iconpath, fs.constants.F_OK)
      await fs.writeFile(iconpath, buffer, 'base64')
    } catch (error) {
      // eslint-disable-next-line no-empty
    }
  } catch (e) {
    console.log(e, app.desc)
  }
}
const fileDisplay = async (filePath: string) => {
  const files = await fs.readdir(filePath)
  files.forEach(async function (filename) {
    const filedir = path.join(filePath, filename)
    const stats = await fs.stat(filedir)
    const isFile = stats.isFile() // 是文件
    const isDir = stats.isDirectory() // 是文件夹
    if (isFile) {
      const appName = filename.split('.')[0]
      const keyWords = [appName]
      let appDetail: any = {}
      try {
        appDetail = shell.readShortcutLink(filedir)
      } catch (e) {
        //
      }
      if (!appDetail.target || appDetail.target.toLowerCase().indexOf('unin') >= 0) return
      // C:/program/cmd.exe => cmd
      keyWords.push(path.basename(appDetail.target, '.exe'))
      if (isZhRegex.test(appName)) {
        // const [, pinyinArr] = translate(appName);
        // const zh_firstLatter = pinyinArr.map((py) => py[0]);
        // // 拼音
        // keyWords.push(pinyinArr.join(''));
        // 缩写
        // keyWords.push(zh_firstLatter.join(''));
      } else {
        const firstLatter = appName
          .split(' ')
          .map((name) => name[0])
          .join('')
        keyWords.push(firstLatter)
      }
      const icon = path.join(os.tmpdir(), 'ProcessIcon', `${encodeURIComponent(appName)}.png`)
      const appInfo = {
        value: 'plugin',
        desc: appDetail.target,
        type: 'app',
        icon,
        pluginType: 'app',
        action: `start "dummyclient" "${appDetail.target}"`,
        keyWords: keyWords,
        name: appName,
        names: JSON.parse(JSON.stringify(keyWords))
      }
      fileLists.push(appInfo)
      await getico(appInfo)
    }
    if (isDir) {
      fileDisplay(filedir) // 递归，如果是文件夹，就继续遍历该文件夹下面的文件
    }
  })
}
export default async () => {
  await fileDisplay(filePath)
  await fileDisplay(startMenu)
  return fileLists
}
